<template>
    <div class="work-order-container">
        <div class="button-group">
            <el-button type="primary" @click="Baoc">保存</el-button>
            <el-button @click="Viesw">取消</el-button>
            <el-button type="success">审核</el-button>
            <el-button type="info" disabled>反审核</el-button>
            <el-button @click="toggleFormVisibility">
                {{ isFormVisible ? '收起' : '展开' }}
            </el-button>
        </div>
        <el-form :model="formData" label-width="100px" v-if="isFormVisible">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="单据编码">
                        <el-input v-model="formData.processId" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="业务类型">
                        <el-select v-model="formData.processtype" placeholder="请选择">
                            <el-option label="装配车间" value="装配车间"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="生产单号">
                        <el-input v-model="formData.processSid" disabled readonly>
                            <template #suffix>
                                <el-link @click="openProductionOrderDialog">选择</el-link>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="跟单编号">
                        <el-input v-model="formData.processGId" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="单据日期">
                        <el-date-picker v-model="formData.processTime" type="date" placeholder="选择日期"
                            readonly></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="操作员">
                        <el-input v-model="formData.processName" disabled readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="生产线">
                        <el-input v-model="formData.processXType" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="物料编码">
                        <el-input v-model="formData.processBId" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="单据状态">
                        <el-input v-model="formData.processState" disabled readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="审核员">
                        <el-input v-model="formData.processYName" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工艺路线">
                        <el-input v-model="formData.processroute" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="物料名称">
                        <el-input v-model="formData.processWname" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="业务状态">
                        <el-select v-model="formData.processAsaste" placeholder="请选择">
                            <el-option label="正常" value="正常"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="审核日期">
                        <el-date-picker v-model="formData.processDTime" disabled type="date"
                            placeholder="选择日期"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工序">
                        <el-input v-model="formData.processzhong" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="质量属性">
                        <el-select v-model="formData.processattribute" placeholder="选择">
                            <el-option label="成品" value="成品"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="完工数量">
                        <el-input v-model="formData.processNumber"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工人">
                        <el-select v-model="formData.processworker" placeholder="请选择工人">
                            <!-- :value 绑定字符串值，确保和 v-model 类型一致 -->
                            <el-option label="陈平安" :value="'陈平安'"></el-option>
                            <el-option label="李佳" :value="'李佳'"></el-option>
                            <el-option label="李健" :value="'李健'"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注信息">
                        <el-input type="textarea" v-model="formData.remark" placeholder="输入备注信息"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 生产订单选择对话框 -->
        <el-dialog v-model="productionOrderDialogVisible" title="选择生产订单" width="80%" destroy-on-close>
            <div class="order-search" style="display: flex; align-items: center; flex-wrap: wrap; margin-bottom: 10px;">
                <el-input placeholder="跟单编号" v-model="searchParams.followNumber" style="flex: 1; margin-right: 10px;" />
                <el-input placeholder="物料编码" v-model="searchParams.materialCode" style="flex: 1; margin-right: 10px;" />
                <el-input placeholder="物料名称" v-model="searchParams.materialName" style="flex: 1; margin-right: 10px;" />
                <div style="display: flex; align-items: center; margin-right: 10px;">
                    <el-date-picker v-model="searchParams.startDate" type="date" placeholder="开始日期"
                        style="margin-right: 10px;" />
                    <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" />
                </div>
                <el-button type="primary" @click="searchProductionOrders">搜索</el-button>
                <el-button @click="queryAllOrders" style="margin-left: 10px;">查询所有</el-button>
            </div>
            <el-table :data="productionOrders" border style="width: 100%;" @row-click="handleRowClick">
                <el-table-column label="跟单编号" prop="tu_status" />
                <el-table-column label="生产订单号" prop="id" />
                <el-table-column label="物料编码" prop="material_code" />
                <el-table-column label="物料名称" prop="name" />
                <el-table-column label="主计量" prop="unit" />
                <el-table-column label="生产数量" prop="production_qty" />
                <el-table-column label="生产日期" prop="production_date" />
                <el-table-column label="选择" width="80">
                    <template #default="{ row }">
                        <el-radio v-model="selectedProductionOrder" :label="row.id"
                            @change="handleRadioChange(row)"></el-radio>
                    </template>
                </el-table-column>
            </el-table>
            <div class="dialog-footer" style="text-align: right; margin-top: 10px;">
                <el-button @click="productionOrderDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmProductionOrder"
                    :disabled="!selectedProductionOrder">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive,onMounted} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useCounterStore } from '@/stores/counter';

const store = useCounterStore();
const router = useRouter();
const route = useRoute();

const Id=route.query.ProcessId;

const formData = reactive({
    processId: '',                // 单据编码
    processtype: '装配车间',       // 业务类型
    processSid: '',               // 生产单号
    processGId: '',               // 跟单编号
    processNumber: '',            // 完工数量
    processTime: new Date(),      // 单据日期
    processName: store.user?.userName || '', // 操作员
    processXType: '',             // 生产线
    processBId: '',               // 物料编码
    processworker: '',            // 工人
    processState: '开立',         // 单据状态
    processYName: '',             // 审核员
    processroute: '',             // 工艺路线
    processWname: '',             // 物料名称
    processAsaste: '正常',        // 业务状态
    processDTime: '',             // 审核日期
    processzhong: '',             // 工序
    processattribute: '成品',     // 质量属性
    remark: ''                    // 备注信息
});

const productionOrderDialogVisible = ref(false);
const workerDialogVisible = ref(false);
const isFormVisible = ref(true);

const searchParams = ref({
    followNumber: '',
    materialCode: '',
    materialName: '',
    startDate: '',
    endDate: '',
    PageIdex: 1,
    PageSize: 15
});

const productionOrders = ref([]);
const selectedOrders = ref([]);
const selectedProductionOrder = ref(null);

// 打开生产订单对话框（关键方法，确保存在）
const openProductionOrderDialog = async () => {
    productionOrderDialogVisible.value = true;
    try {
        const response = await axios.get("https://localhost:7006/api/Production/Production_orderFile", {
            params: searchParams.value
        });
        productionOrders.value = response.data.data.list || [];
        await nextTick();
    } catch (error) {
        console.error('获取订单数据出错：', error);
        ElMessage.error('获取生产订单失败');
    }
};

const openWorkerDialog = () => {
    workerDialogVisible.value = true;
    openProductionOrderDialog()
};

const toggleFormVisibility = () => {
    isFormVisible.value = !isFormVisible.value;
};

const searchProductionOrders = async () => {
    try {
        const response = await axios.get('http://your-api-domain.com/api/production-orders', {
            params: searchParams
        });
        productionOrders.value = response.data.list || [];
    } catch (error) {
        ElMessage.error('搜索生产订单失败，请重试');
        console.error(error);
    }
};

const queryAllProductionOrders = async () => {
    try {
        const response = await axios.get('http://your-api-domain.com/api/all-production-orders', {
            params: { page: 1, size: 100 }
        });
        productionOrders.value = response.data.list || [];
    } catch (error) {
        ElMessage.error('查询所有生产订单失败，请重试');
        console.error(error);
    }
};

const handleSelectionChange = (val) => {
    selectedOrders.value = val;
};

const handleRowClick = (row) => {
    selectedProductionOrder.value = row.id;
};

const handleRadioChange = (row) => {
    formData.processSid = row.id;
    formData.processXType = row.production_line;
    formData.processYName = row.auditor;
    formData.processBId = row.material_code;
    formData.processWname = row.name;
    formData.processAsaste = row.business_status;
    formData.processState = row.status;
};

const confirmProductionOrder = () => {
    if (selectedProductionOrder.value) {
        const selectedOrder = productionOrders.value.find(
            order => order.id === selectedProductionOrder.value
        );
        if (selectedOrder) {
            // 直接使用已选中的订单数据进行赋值
            formData.processSid = selectedOrder.id; // 生产单号
            formData.processGId = selectedOrder.tu_status; // 跟单编号（假设batch_number对应）
            formData.processXType = selectedOrder.production_line; // 生产线
            formData.processBId = selectedOrder.material_code; // 物料编码
            formData.processWname = selectedOrder.name; // 物料名称
            formData.processroute = selectedOrder.process_route; // 工艺路线（需确认字段名）
            formData.processzhong = selectedOrder.business_type; // 工序（需确认字段名）
            formData.processDTime = new Date();
            formData.processYName = "无";
            formData.processroute = "车钳=>钻孔=>热处理";

            productionOrderDialogVisible.value = false; // 关闭对话框
            ElMessage.success('数据已填充');
        } else {
            ElMessage.error('未找到对应订单信息');
        }
    } else {
        ElMessage.warning('请选择一条生产订单');
    }
};

const selectWorker = () => {
    workerDialogVisible.value = false;
};

const Viesw = () => {
    router.push('/ProcessReportForm');
};

const Baoc = () => {
    axios.post('https://localhost:7207/api/Production/ProcessA', formData).then((res) => {
        if (res.data.code === 212) {
            ElMessage.success('保存成功');
            router.push('/ProcessReportForm');
        } else {
            ElMessage.error('保存失败');
        }
    }).catch((error) => {
        ElMessage.error('保存时发生错误，请稍后重试');
        console.error(error);
    });
};

const ShowProductShow=()=>{
    axios.get(`https://localhost:7006/api/Process/ProcessFile?ProcessId=${Id}`).then((res=>{
        var data=res.data.data[0]
        console.log(data)
         // 字段映射（确保API返回字段与formData字段一致）
        formData.processId = data.processId;
        formData.processtype = data.processtype;
        formData.processSid = data.processSid;
        formData.processGId = data.processGId;
        formData.processNumber = data.processNumber;
        
        // 日期处理（如果API返回字符串，需转换为Date对象）
        formData.processTime = data.processTime ? new Date(data.processTime) : new Date();
        formData.processDTime = data.processDTime ? new Date(data.processDTime) : ''; // 审核日期
        
        formData.processName = data.processName;
        formData.processXType = data.processXType;
        formData.processBId = data.processBId;
        formData.processworker = data.processworker;
        formData.processState = data.processState;
        formData.processYName = data.processYName;
        formData.processroute = data.processroute;
        formData.processWname = data.processWname;
        formData.processAsaste = data.processAsaste;
        formData.processzhong = data.processzhong;
        formData.processattribute = data.processattribute;
        formData.remark = data.remark || ''; // 备注信息
    }))
}


onMounted(()=>{
    ShowProductShow()
})
</script>

<style scoped>
.work-order-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.button-group {
    margin-bottom: 20px;
    text-align: right;
    border-bottom: 1px solid #ebedf0;
    padding-bottom: 15px;
}

.el-form-item {
    margin-bottom: 12px;
}

.el-dialog__body {
    padding: 20px 30px;
}
</style>